package com.xmqian.app.project.common.helper;

import com.coszero.utils.utils.LogX;
import com.coszero.utils.utils.StringUtils;
import com.coszero.utils.utils.TimeUtils;
import com.coszero.ui.dialog.ToastUtils;
import com.coszero.common.dialog.CommonDialogView;
import com.coszero.common.network.HttpErrorCode;
import com.coszero.common.network.OkHttpUtils;
import com.xmqian.kotlinApp.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

public class RequestHelper {
    private static String TAG = "###食刻 RequestHelper";
    private static RequestHelper requestHelper;

    public static RequestHelper getInstance() {
        if (requestHelper == null) {
            requestHelper = new RequestHelper();
        }
        return requestHelper;
    }
// <editor-fold desc="网络请求">

    /**
     * post请求
     *
     * @param json jsonobject
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public void post(String url, JSONObject json, OkHttpUtils.HttpCallBack httpCallBack) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        post(url, requestBody, httpCallBack);
    }

    /**
     * post请求
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public void post(String url, RequestBody requestBody, OkHttpUtils.HttpCallBack httpCallBack) {
        Request.Builder builder = new Request.Builder()
                .addHeader("appVersion", BuildConfig.VERSION_NAME);
        OkHttpUtils.getInstance().post(url, requestBody, builder, new OkHttpUtils.HttpCallBack() {
            @Override
            public void onSucceed(String result) {
                if (!isErrorRequest(result)) {
                    httpCallBack.onSucceed(result);
                } else {
                    httpCallBack.onFail(new JSONException(result), "json error");
                }
            }

            @Override
            public void onFail(Exception result, String msg) {

                httpCallBack.onFail(result, "request fail");
            }
        });
    }

    /**
     * get请求
     */
    public void get(String url, OkHttpUtils.HttpCallBack httpCallBack) {
        Request.Builder builder = new Request.Builder()
                .addHeader("appVersion", BuildConfig.VERSION_NAME);
        OkHttpUtils.getInstance().get(url, builder, new OkHttpUtils.HttpCallBack() {
            @Override
            public void onSucceed(String result) {
                if (!isErrorRequest(result)) {
                    httpCallBack.onSucceed(result);
                } else {
                    httpCallBack.onFail(new JSONException(result), "json error");
                }
            }

            @Override
            public void onFail(Exception result, String msg) {
                httpCallBack.onFail(result, "request fail");

            }
        });
    }

    public void get(String url, Map<String, String> map, OkHttpUtils.HttpCallBack httpCallBack) {
        StringBuffer buffer = new StringBuffer(url + "?");
        if (map.size() > 0) {
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                buffer.append(key + "=" + value + "&");
            }
        }
        get(buffer.substring(0, buffer.length() - 1), httpCallBack);
    }

    /**
     * 多文件上传
     *
     * @param localImage 文件路径
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public void postFiles(String url, List<String> localImage, OkHttpUtils.HttpCallBack httpCallBack) {
        Request.Builder builder = new Request.Builder()
                .addHeader("appVersion", BuildConfig.VERSION_NAME);
        OkHttpUtils.getInstance().postFile(url, builder, localImage, new OkHttpUtils.HttpCallBack() {
            @Override
            public void onSucceed(String result) {
                httpCallBack.onSucceed(result);
            }

            @Override
            public void onFail(Exception result, String msg) {

                httpCallBack.onFail(result, "upload fail");
            }
        });
    }

    /**
     * 单文件上传
     *
     * @param file 文件流
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public void postFile(String url, File file, OkHttpUtils.HttpCallBack httpCallBack) {
        Request.Builder builder = new Request.Builder()
                .addHeader("appVersion", BuildConfig.VERSION_NAME);
        OkHttpUtils.getInstance().postFile(url, builder, file, new OkHttpUtils.HttpCallBack() {
            @Override
            public void onSucceed(String result) {
                httpCallBack.onSucceed(result);
            }

            @Override
            public void onFail(Exception result, String msg) {
                httpCallBack.onFail(result, "upload fail");
            }
        });
    }
    //</editor-fold>

    // <editor-fold desc="请求回调拦截处理" defaultstate="collapsed">

    /**
     * 判断是否为错误请求
     *
     * @return 错误请求为code不为0 返回 true,,如果code==0,或者需要特殊处理的code返回false
     */
    private boolean isErrorRequest(String result) {
        try {
            if (StringUtils.isEmpty(result) || result.equals(new JSONObject().toString())) {
                LogX.d("###", "isErrorRequest 返回的请求数据为空");
                return false;
            }
            JSONObject object = new JSONObject(result);
            String code = object.getString(HttpErrorCode.CODE);
            String message = object.getString(HttpErrorCode.MESSGE);
            if (!HttpErrorCode.SUCCESS_CODE.equals(code)) {
                switch (code) {
                    //这里过滤需要重新登录的code
                    case HttpErrorCode.LOGINOUT://账号异地登录
                        showLoginErrorDialog(code, message);
                        break;
                    //这里是用来过滤不需要提示的，直接在结果中做处理
                    case HttpErrorCode.ERROR_MSG:
                        return false;
                    default:
                        //这里的请求错误直接过滤掉，不在结果中做处理
                        ToastUtils.showMsg(message);
                        return true;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            LogX.d("###", "isErrorRequest  数据解析失败：" + e.getMessage() + "\n 原始数据为：" + result);
        }
        return false;
    }

    /**
     * 登录异常弹窗
     *
     * @param code code
     * @param messge msg
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    private void showLoginErrorDialog(String code, String messge) {
            /*"code":"FA000410",
    	"message":"你的食刻帐号于<1587545511000>在未知设备上通过手机号验证码登录(手机号15056098873)。如果这不是你的操作，你的手机号验证码已经泄漏。请重新登录！"*/
        if (!StringUtils.isEmpty(messge) && messge.contains("<") && messge.contains(">")) {
            try {
                int startIndex = messge.indexOf("<");
                int endIndex = messge.indexOf(">");
                String substring = messge.substring(startIndex + 1, endIndex);
                Long longTime = Long.valueOf(substring);
                String formatDate = TimeUtils.getFormatDate(new Date(longTime), TimeUtils.DF_YYYY_MM_DD_HH_MM);
                String newMessge = messge.replace("<" + substring + ">", formatDate);
                System.out.println(newMessge);
                CommonDialogView.showLoginErrorDialog(code, newMessge);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            CommonDialogView.showLoginErrorDialog(code, messge);
        }
    }
    //</editor-fold>
}
